﻿@{
    ViewData["Title"] = "Index";
    Layout = "_OridinaryPage";
}

@section Header{
    <!-- BootStrap-table -->
    <link rel="stylesheet" href="~/js/plugins/bootstrap-table/bootstrap-table.css" />
    <link rel="stylesheet" href="~/js/plugins/jquery-treegrid/css/jquery.treegrid.css" />
}

<section>
    <!--<h2>
        <small></small>
    </h2>-->
    <ol class="breadcrumb breadcrumb-pd clear-mgb bg-transparent">
        <li><a href="#"><i class="fa fa-dashboard"></i> 系统管理</a></li>
        <li class="active">定时任务管理</li>
    </ol>
</section>

<!-- Main content -->
<section class="content-mini clear-pdt clear-pdb">
    <div class="row">
        <div class="col-xs-12">
            <div class="box clear-mgb clearBoxTopBorder clearShadow">
                <!--<div class="box-header">
                    <h3 class="box-title"></h3>
                </div>-->
                <!-- /.box-header -->
                <div class="box-body clear-pd">
                    <div id="toolbar" class="btn-group">
                        @if (BaseHelper.HasPermission(SysJobBtn.Add))
                        {
                            <button id="btnAdd" type="button" class="btn btn-default" data-toggle="modal" data-target="#addEditModal">
                                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>添加
                            </button>
                        }
                        @if (BaseHelper.HasPermission(SysJobBtn.Edit))
                        {
                            <button id="btnEdit" type="button" class="btn btn-default" data-toggle="modal">
                                <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
                            </button>
                        }
                        @if (BaseHelper.HasPermission(SysJobBtn.Delete))
                        {
                            <button id="btnDelete" type="button" class="btn btn-default" data-toggle="modal">
                                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
                            </button>
                        }
                    </div>
                    <table id="dataInfos" class="table table-bordered table-hover"></table>
                </div>
                <!-- /.box-body -->
            </div>
            <!-- /.box -->
        </div>
        <!-- /.col -->
    </div>
    <!-- /.row -->
</section>
<!-- /.content -->
<!-- addEditModal---start -->
<div id="addEditModal" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="addEditModal">
    <div class="modal-dialog modal-md" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">添加任务</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="addEditForm">
                    <input type="hidden" class="clear" id="addEditJobId" name="JobId" value="" />
                    <div class="form-group">
                        <label for="addEditJobName" class="col-sm-2 control-label">任务名称</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control clear" id="addEditJobName" name="JobName" placeholder="任务名称" maxlength="100">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="addEditJobType" class="col-sm-2 control-label">任务类型</label>
                        <div class="col-sm-9">
                            @*<input type="text" class="form-control clear" id="addEditJobType" name="JobType" placeholder="任务类型">*@
                            <select id="addEditJobType" name="JobType" class="form-control">
                                <option value="0">本地任务</option>
                                <option value="1">外部接口任务</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="addEditJobCall" class="col-sm-2 control-label">任务地址</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control clear" id="addEditJobCall" name="JobCall" placeholder="任务地址" maxlength="500">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="addEditJobCallParams" class="col-sm-2 control-label">任务参数</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control clear" id="addEditJobCallParams" name="JobCallParams" placeholder="任务参数" maxlength="500">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="addEditCron" class="col-sm-2 control-label">Cron表达式</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control clear" id="addEditCron" name="Cron" placeholder="Cron表达式" maxlength="50">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="addEditStatus" class="col-sm-2 control-label">运行状态</label>
                        <div class="col-sm-9">
                            <select id="addEditStatus" name="Status" class="form-control">
                                <option value="1">正在运行</option>
                                <option value="0">停止</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="addEditRemarks" class="col-sm-2 control-label">备注</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control clear" id="addEditRemarks" name="Remarks" placeholder="备注" value="无" maxlength="128">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" id="btnAddEditSubmit" class="btn btn-primary">提交</button>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $("#btnAddEditSubmit").click(function () {
        var jobId = $("#addEditJobId").val();
        var jobName = $("#addEditJobName").val();
        var jobType = $("#addEditJobType :selected").val();
        var jobCall = $("#addEditJobCall").val();
        var jobCallParams = $("#addEditJobCallParams").val();
        var cron = $("#addEditCron").val();
        var status = $("#addEditStatus :selected").val();
        var remarks = $("#addEditRemarks").val();
        if (jobName == null || jobName.trim() == "") {
            alert("请输入任务名称！");
            $("#addEditJobName").focus();
            return;
        }
        if (jobType == null || jobType.trim() == "") {
            alert("请选择任务类型！");
            $("#addEditJobType").focus();
            return;
        }
        if (jobCall == null || jobCall.trim() == "") {
            alert("请输入任务地址！");
            $("#addEditJobCall").focus();
            return;
        }
        if (cron == null || cron.trim() == "") {
            alert("请输入Cron表达式！");
            $("#addEditCron").focus();
            return;
        }
        if (status == null || status.trim() == "") {
            alert("请选择运行状态！");
            $("#addEditStatus").focus();
            return;
        }
        if (remarks == null || remarks.trim() == "") {
            alert("请输入备注！");
            $("#addEditRemarks").focus();
            return;
        }
        IndexBtnDisabled();
        $.ajax({
            type: "post",
            url: IsNullOrEmpty(jobId) ? "/Sys/Sys_Job/Add" : "/Sys/Sys_Job/Edit",
            data: $("#addEditForm").serialize(),
            dataType: "json",
            success: function (data) {
                if (data.Success) {
                    alert(data.Message);
                    $("#addEditModal").modal('hide');
                    $("button[name='refresh']").click();
                } else {
                    alert(data.Message);
                }
                IndexBtnEnabled();
            },
            error: function (err) { }
        });
    });
</script>
<!-- addEditModal---end -->

@section Scripts{
    <script src="~/js/plugins/bootstrap-table/bootstrap-table.min.js"></script>
    <script src="~/js/plugins/bootstrap-table/locale/bootstrap-table-zh-CN.js"></script>
    <script src="~/js/plugins/zTree/js/jquery.ztree.all.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            //1.初始化Table
            var oTable = new TableInit();
            oTable.Init();
        });

        var TableInit = function () {
            var oTableInit = new Object();
            //初始化Table
            oTableInit.Init = function () {
                $('#dataInfos').bootstrapTable({
                    url: '/Sys/Sys_Job/GetPageList',    //请求后台的URL（*）
                    method: 'get',                      //请求方式（*）
                    toolbar: '#toolbar',                //工具按钮用哪个容器
                    striped: true,                      //是否显示行间隔色
                    cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                    pagination: true,                   //是否显示分页（*）
                    sortable: true,                     //是否启用排序
                    sortName: "CreateTime",             //排序字段
                    sortOrder: "desc",                  //排序方式
                    queryParams: oTableInit.queryParams,//传递参数（*）
                    sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                    pageNumber: 1,                      //初始化加载第一页，默认第一页
                    pageSize: 15,                       //每页的记录行数（*）
                    pageList: [10, 15, 20, 30, 50],     //可供选择的每页的行数（*）
                    search: true,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
                    searchOnEnterKey: true,
                    strictSearch: true,
                    showColumns: true,                  //是否显示所有的列
                    showRefresh: true,                  //是否显示刷新按钮
                    minimumCountColumns: 2,             //最少允许的列数
                    clickToSelect: true,                //是否启用点击选中行
                    //height: 811,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
                    uniqueId: "JobId",                  //每一行的唯一标识，一般为主键列
                    showToggle: true,                   //是否显示详细视图和列表视图的切换按钮
                    cardView: false,                    //是否显示详细视图
                    detailView: false,                  //是否显示父子表
                    columns: [{
                        checkbox: true
                    }, {
                        field: 'JobId',
                        title: '任务Id'
                    }, {
                        field: 'JobName',
                        title: '任务名称'
                    }, {
                        field: 'JobType',
                        title: '任务类型',
                        formatter: function (value, row, index) {
                            if (value == "0") {
                                return "本地任务";
                            }
                            if (value == "1") {
                                return "外部接口任务";
                            }
                            return "未知类型";
                        }
                    }, {
                        field: 'JobCall',
                        title: '任务地址'
                    }, {
                        field: 'JobCallParams',
                        title: '任务参数'
                    }, {
                        field: 'Cron',
                        title: 'Cron表达式'
                    }, {
                        field: 'Status',
                        title: '运行状态',
                        formatter: function (value, row, index) {
                            if (value == "0") {
                                return "停止";
                            }
                            if (value == "1") {
                                return "正在运行";
                            }
                            return "未知类型";
                        }
                    }, {
                        field: 'CreateTime',
                        title: '创建时间',
                        sortable: true,
                        formatter: function (value, row, index) {
                            return getFormatDate(value);
                        }
                    }, {
                        field: 'Code',
                        title: '操作',
                        formatter: 'operateFormatter'
                    }],
                    onLoadSuccess: function (res) {  //加载成功时执行
                        //console.info("加载成功");
                    },
                    onLoadError: function () {  //加载失败时执行
                        //console.info("加载数据失败");
                    }
                });
            };

            //得到查询的参数
            oTableInit.queryParams = function (params) {
                var temp = {   //这里键的名字和控制器的变量名必须一致，如有变动此处和控制器要一起改
                    rowsPerPage: params.limit,  //每页数据行数
                    offsetRows: params.offset,  //已偏移行数
                    sortName: params.sort,
                    sortOrder: params.order,
                    search: $("div.search input").val(),
                    //search: params.search
                };
                return temp;
            };
            return oTableInit;
        };

        //格式化操作列的内容
        function operateFormatter(value, row, index) {
            var array = [];
            @if (BaseHelper.HasPermission(SysJobBtn.Edit))
            {
                @:array.push("<a onclick='showEditModal(" + JSON.stringify(row) + ")' class='operateLink'><i class='fa fa-pencil-square-o' ></i>&nbsp;编辑</a>");
            }
            return array.join('');
        }

        $("#btnAdd").click(function () {
            $(".clear").val('');
            $("#addEditModal .modal-title").text('添加定时任务');
        });

        $("#btnEdit").click(function () {
            var selections = $('#dataInfos').bootstrapTable('getSelections');
            if (selections.length < 1) {
                alert("请选择要修改的条目！");
                return;
            }
            if (selections.length > 1) {
                alert("只能选择一条要修改的条目！");
                return;
            }
            showEditModal(selections[0]);
        });

        function showEditModal(row) {
            if (IsNullOrEmpty(row.JobId)) {
                alert("数据异常，请联系管理员！");
                return;
            }
            $("#addEditModal .modal-title").text('编辑定时任务');
            $("#addEditJobId").val(row.JobId);
            $("#addEditJobName").val(row.JobName);
            $("#addEditJobType").val(row.JobType);
            $("#addEditJobCall").val(row.JobCall);
            $("#addEditJobCallParams").val(row.JobCallParams);
            $("#addEditCron").val(row.Cron);
            $("#addEditStatus").val(row.Status);
            $("#addEditRemarks").val(row.Remarks);
            $("#addEditModal").modal('show');
        }

        $("#btnDelete").click(function () {
            var selections = $('#dataInfos').bootstrapTable('getSelections');
            if (selections.length < 1) {
                alert("请选择要删除的条目！");
                return;
            }
            if (!confirm("请确认删除！")) return;
            var ids = "";
            for (var i = 0; i < selections.length; i++) {
                ids += selections[i].JobId + ",";
            }
            if (ids.endsWith(",")) {
                ids = ids.substr(0, ids.length - 1);
            }
            $.ajax({
                type: "post",
                url: "/Sys/Sys_Job/Delete",
                data: "ids=" + ids,
                dataType: "json",
                success: function (data) {
                    if (data.Success) {
                        alert(data.Message);
                        $("button[name='refresh']").click();
                    } else {
                        alert(data.Message);
                    }
                },
                error: function (err) { }
            });
        });
    </script>
}